package com.mrx.xgateway.controller;

import com.mrx.xgateway.model.Config;
import com.mrx.xgateway.utils.ConfigUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Mr.X
 * @since 2024-03-10 下午 7:17:16
 */
@RestController
@RequestMapping("/config")
public class ConfigController {

    @GetMapping("/getConfig")
    public Collection<Config> getConfig() {
        return ConfigUtils.loadConfig();
    }

    @PostMapping("/addConfig")
    public Collection<Config> addConfig(@RequestBody List<Config> forwardConfig) {
        Map<String, Config> configMap = ConfigUtils.loadConfig().stream()
                .collect(Collectors.toMap(Config::getPath, Function.identity()));
        for (Config config : forwardConfig) {
            Config oldConfig = configMap.get(config.getPath());
            if (oldConfig != null) {
                // 若 path 已存在, 但 forward 不同, 或是 stripPath 不同 则表明是 更新
                if (!oldConfig.getForward().equals(config.getForward()) || !Objects.equals(oldConfig.getStripPath(), config.getStripPath())) {
                    configMap.put(config.getPath(), config);
                }
            } else {
                // 若 path 不存在 则表明是 新增
                configMap.put(config.getPath(), config);
            }
        }
        return ConfigUtils.writeConfig(configMap.values());
    }

    @PostMapping("/delConfig")
    public Collection<Config> delConfig(@RequestBody List<String> delPath) {
        List<Config> removedConfig = ConfigUtils.loadConfig().stream()
                .filter(it -> !delPath.contains(it.getPath())).collect(Collectors.toList());
        return ConfigUtils.writeConfig(removedConfig);
    }

}
